package com.example.blog.utils;

import com.example.blog.constants.Constants;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParser;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;

import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class JwtUtils {
    //过期毫秒时长
    public  static final long EXPIRATION = 30 * 60 * 1000;

    //密钥
    private static final String secretString = "nFGwRQOjKbiyPV4Y0/fUwPFwScbFFiB4H8Ls7J5l0cw=";

    //签名密钥
    private static final Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretString));

    //生成token
    public static String genJwtToken(Map<String, Object> claim) {
        String token = Jwts.builder()
                .setClaims(claim) //设置信息
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))//设置过期时间
                .signWith(key)//设置签名
                .compact();//生成JWT令牌并输出
        return token;
    }

    /**
     *
     * 校验token
     * 返回null代表校验失败
     */
    public static Claims parseToken(String token) {
        JwtParser build = Jwts.parserBuilder().setSigningKey(key).build();
        Claims claims = null;
        try {
            claims = build.parseClaimsJws(token).getBody();
        }catch (Exception e) {
            log.error("token解析失败：{}", token);
            return null;
        }
        return claims;
    }

    public static Integer getIdInToken(String token) {
        Claims claims = JwtUtils.parseToken(token);
        return claims.get(Constants.TOKEN_ID, Integer.class);
    }
}
